<template>
  <div class="user-profile">
    <h2>个人中心</h2>
    
    <div class="profile-section">
      <h3>基本信息</h3>
      <div class="profile-info">
        <div class="info-row">
          <span class="label">用户名：</span>
          <span class="value">{{ userInfo.user_name }}</span>
        </div>
        <div class="info-row">
          <span class="label">身份证号：</span>
          <span class="value">{{ maskIdNumber(userInfo.id_card) }}</span>
        </div>
        <div class="info-row">
          <span class="label">手机号：</span>
          <span v-if="!editing" class="value">{{ userInfo.phone }}</span>
          <input v-else v-model="editForm.phone" type="tel" class="edit-input" placeholder="请输入手机号" />
        </div>
        <div class="info-row">
          <span class="label">紧急联系人：</span>
          <span v-if="!editing" class="value">{{ userInfo.emergency_name || '未设置' }}</span>
          <input v-else v-model="editForm.emergency_name" type="text" class="edit-input" placeholder="请输入紧急联系人" />
        </div>
        <div class="info-row">
          <span class="label">紧急联系人电话：</span>
          <span v-if="!editing" class="value">{{ userInfo.emergency_phone || '未设置' }}</span>
          <input v-else v-model="editForm.emergency_phone" type="tel" class="edit-input" placeholder="请输入紧急联系人电话" />
        </div>
        <div class="info-row">
          <span class="label">联系地址：</span>
          <span v-if="!editing" class="value">{{ userInfo.address || '未设置' }}</span>
          <input v-else v-model="editForm.address" type="text" class="edit-input" placeholder="请输入联系地址" />
        </div>
        <div class="info-row">
          <span class="label">注册时间：</span>
          <span class="value">{{ userInfo.create_time }}</span>
        </div>
        <div class="info-row">
          <span class="label">账号状态：</span>
          <span :class="['value', getStatusClass(userInfo.status)]">
            {{ getStatusText(userInfo.status) }}
          </span>
        </div>
      </div>
    </div>
    
    <div class="action-buttons">
      <button v-if="!editing" @click="startEditing" class="edit-btn">编辑信息</button>
      <button v-if="editing" @click="saveChanges" class="save-btn">保存修改</button>
      <button v-if="editing" @click="cancelEditing" class="cancel-btn">取消</button>
      <button @click="showChangePassword = true" class="password-btn">修改密码</button>
    </div>
    
    <!-- 修改密码弹窗 -->
    <div v-if="showChangePassword" class="modal-overlay" @click="closeChangePassword">
      <div class="modal-content" @click.stop>
        <h3>修改密码</h3>
        <div class="password-form">
          <div class="form-group">
            <label for="oldPassword">原密码</label>
            <input type="password" v-model="passwordForm.oldPassword" id="oldPassword" placeholder="请输入原密码" />
          </div>
          <div class="form-group">
            <label for="newPassword">新密码</label>
            <input type="password" v-model="passwordForm.newPassword" id="newPassword" placeholder="请输入新密码" />
          </div>
          <div class="form-group">
            <label for="confirmPassword">确认新密码</label>
            <input type="password" v-model="passwordForm.confirmPassword" id="confirmPassword" placeholder="请确认新密码" />
          </div>
        </div>
        <div class="modal-buttons">
          <button @click="changePassword" class="confirm-btn">确认修改</button>
          <button @click="closeChangePassword" class="close-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import api from '../../utils/axiosConfig'

export default {
  name: 'UserProfile',
  setup() {
    const userStore = useUserStore()
    const editing = ref(false)
    const showChangePassword = ref(false)
    
    // 用户信息，根据数据库表结构定义，提供默认初始值确保页面不会空白
    const userInfo = reactive({
      user_id: '',
      user_name: userStore.username || '加载中...',
      id_card: '',
      phone: '加载中...',
      emergency_name: '',
      emergency_phone: '',
      address: '',
      create_time: '加载中...',
      status: 1
    })
    
    const editForm = reactive({
      phone: '',
      emergency_name: '',
      emergency_phone: '',
      address: ''
    })
    
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 获取用户状态样式类名
    const getStatusClass = (status) => {
      switch (status) {
        case 1: return 'status-active'
        case 0: return 'status-pending'
        case 2: return 'status-inactive'
        default: return ''
      }
    }
    
    // 获取用户状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 1: return '正常'
        case 0: return '待审核'
        case 2: return '已禁用'
        default: return '未知'
      }
    }
    
    // 身份证号掩码处理
    const maskIdNumber = (idCard) => {
      if (!idCard || idCard.length < 10) return idCard
      return idCard.substring(0, 6) + '********' + idCard.substring(14)
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '未知时间'
      try {
        const date = new Date(dateTime)
        if (isNaN(date.getTime())) {
          return '时间格式错误'
        }
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        console.error('日期格式化失败:', error)
        return dateTime || '未知时间'
      }
    }
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        // 首先检查用户是否已登录
        console.log('检查用户登录状态:', userStore.isLoggedIn)
        
        // 输出userStore的完整信息用于调试
        console.log('userStore完整信息:', {
          isLoggedIn: userStore.isLoggedIn,
          username: userStore.username,
          role: userStore.role,
          userInfoKeys: Object.keys(userStore.userInfo)
        })
        
        // 尝试从多个可能的位置获取userId
        let userId = userStore.userInfo.userId || 
                    userStore.userInfo.user_id || 
                    userStore.user_id || 
                    userStore.userId
        
        // 检查是否存在嵌套的userInfo对象
        if (!userId && userStore.userInfo.userInfo) {
          userId = userStore.userInfo.userInfo.userId || 
                   userStore.userInfo.userInfo.user_id
          console.log('从嵌套的userInfo对象获取的userId:', userId)
        }
        
        console.log('正在请求用户信息，userId:', userId)
        
        // 如果还是无法获取，尝试从localStorage直接读取
        if (!userId) {
          const localStorageUserInfo = localStorage.getItem('userInfo')
          if (localStorageUserInfo) {
            try {
              const parsedUserInfo = JSON.parse(localStorageUserInfo)
              // 检查直接的userId
              userId = parsedUserInfo.userId || parsedUserInfo.user_id
              
              // 如果直接获取不到，检查是否存在嵌套的userInfo对象
              if (!userId && parsedUserInfo.userInfo) {
                userId = parsedUserInfo.userInfo.userId || parsedUserInfo.userInfo.user_id
                console.log('从localStorage中嵌套的userInfo对象获取的userId:', userId)
              } else {
                console.log('从localStorage获取的userId:', userId)
              }
            } catch (e) {
              console.error('解析localStorage中的userInfo失败:', e)
            }
          }
        }
        
        // 检查userId是否存在
        if (!userId) {
          console.error('未找到用户ID，但登录状态为:', userStore.isLoggedIn)
          console.error('localStorage中的userInfo:', localStorage.getItem('userInfo'))
          
          // 如果已登录但没有userId，提示用户刷新页面或重新登录
          if (userStore.isLoggedIn) {
            alert('登录信息不完整，请刷新页面或重新登录')
          } else {
            alert('未找到用户ID，请先登录')
          }
          return
        }
        console.log('请求URL:', `/user/${userId}`)
        const response = await api.get(`/user/${userId}`)
        console.log('API响应数据:', response)
        const data = response.data
        console.log('用户数据:', data)
        
        // 更新用户信息，注意后端返回的是驼峰命名法
        userInfo.user_id = data.userId || ''
        userInfo.user_name = data.userName || userStore.username || '未知用户'
        userInfo.id_card = data.idCard || ''
        userInfo.phone = data.phone || '未设置'
        userInfo.emergency_name = data.emergencyName || ''
        userInfo.emergency_phone = data.emergencyPhone || ''
        userInfo.address = data.address || ''
        userInfo.create_time = formatDateTime(data.createTime)
        userInfo.status = data.status !== undefined ? data.status : 1
        
        // 同时更新编辑表单的初始值
        editForm.phone = userInfo.phone
        editForm.emergency_name = userInfo.emergency_name
        editForm.emergency_phone = userInfo.emergency_phone
        editForm.address = userInfo.address
        
        console.log('更新后的用户信息:', userInfo)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        console.error('错误详情:', error.response || error.message)
        alert('获取用户信息失败，请稍后重试')
      }
    }
    

    
    const startEditing = () => {
      editing.value = true
      // 复制当前值到编辑表单
      editForm.phone = userInfo.phone
      editForm.emergency_name = userInfo.emergency_name
      editForm.emergency_phone = userInfo.emergency_phone
      editForm.address = userInfo.address
    }
    
    const saveChanges = async () => {
      // 表单验证
      if (!editForm.phone) {
        alert('请输入手机号')
        return
      }
      
      // 构建请求数据，使用驼峰命名法与后端保持一致，移到try外部以解决作用域问题
      const updateData = {
        userId: userInfo.user_id,
        userName: userInfo.user_name,
        phone: editForm.phone,
        emergencyName: editForm.emergency_name,
        emergencyPhone: editForm.emergency_phone,
        address: editForm.address,
        userType: userInfo.user_type || 1 // 添加用户类型字段，默认为普通用户(1)以避免"用户类型不能为空"错误
      }
      
      try {
        
        console.log('准备更新用户信息:', updateData)
        
        // 使用PUT方法调用API，与后端Controller保持一致
        const response = await api.put('/user', updateData)
        
        console.log('更新用户信息响应:', response)
        
        if (response.status === 200) {
          // 更新本地用户信息
          userInfo.phone = editForm.phone || userInfo.phone
          userInfo.emergency_name = editForm.emergency_name || userInfo.emergency_name
          userInfo.emergency_phone = editForm.emergency_phone || userInfo.emergency_phone
          userInfo.address = editForm.address || userInfo.address
          
          editing.value = false
          alert('信息更新成功！')
          console.log('本地用户信息已更新')
        } else {
          console.error('更新失败，状态码:', response.status)
          alert('更新失败，服务器返回错误')
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        console.error('错误详情:', error.response || error.message)
        console.error('响应数据:', error.response?.data || '无响应数据')
        console.error('请求数据:', updateData)
        alert('更新失败，请稍后重试。错误详情：' + (error.response?.data?.message || error.message))
      }
    }
    
    const cancelEditing = () => {
      editing.value = false
    }
    
    const changePassword = async () => {
      // 验证密码
      if (!passwordForm.oldPassword) {
        alert('请输入原密码')
        return
      }
      if (!passwordForm.newPassword) {
        alert('请输入新密码')
        return
      }
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        alert('两次输入的新密码不一致')
        return
      }
      
      try {
        // 构建请求数据，使用正确的字段名
        const passwordData = {
          userId: userInfo.user_id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        }
        
        console.log('准备修改密码，用户ID:', passwordData.userId)
        
        // 调用修改密码API
        const response = await api.post('/user/changePassword', passwordData)
        
        console.log('修改密码响应:', response)
        
        // 检查响应状态和数据
        if (response.status === 200) {
          // 根据后端返回的数据格式进行判断
          if (response.data > 0 || response.data.success || response.data === true) {
            alert('密码修改成功！')
            closeChangePassword()
            console.log('密码修改成功')
          } else {
            alert('原密码错误或修改失败')
            console.warn('修改密码失败，返回数据:', response.data)
          }
        } else {
          console.error('修改密码失败，状态码:', response.status)
          alert('修改密码失败，服务器返回错误')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        console.error('错误详情:', error.response || error.message)
        alert('修改密码失败，请稍后重试')
      }
    }
    
    const closeChangePassword = () => {
      showChangePassword.value = false
      // 重置密码表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }
    
    // 组件挂载时获取用户信息
    onMounted(() => {
      fetchUserInfo()
    })
    
    return {
      userInfo,
      editing,
      editForm,
      showChangePassword,
      passwordForm,
      maskIdNumber,
      getStatusClass,
      getStatusText,
      startEditing,
      saveChanges,
      cancelEditing,
      changePassword,
      closeChangePassword
    }
  }
}
</script>

<style scoped>
.user-profile {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.user-profile h2 {
  color: #333;
  margin-bottom: 20px;
}

.profile-section {
  margin-bottom: 30px;
}

.profile-section h3 {
  color: #606266;
  margin-bottom: 15px;
}

.profile-info {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.label {
  width: 120px;
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
  flex: 1;
}

.status-active {
  color: #67c23a;
}

.status-inactive {
  color: #f56c6c;
}

.edit-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.edit-btn,
.save-btn,
.cancel-btn,
.password-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.edit-btn {
  background-color: #409eff;
  color: #fff;
}

.edit-btn:hover {
  background-color: #66b1ff;
}

.save-btn {
  background-color: #67c23a;
  color: #fff;
}

.save-btn:hover {
  background-color: #85ce61;
}

.cancel-btn {
  background-color: #f0f2f5;
  color: #606266;
}

.cancel-btn:hover {
  background-color: #e6e8eb;
}

.password-btn {
  background-color: #e6a23c;
  color: #fff;
}

.password-btn:hover {
  background-color: #ebb563;
}

/* 账号状态样式 */
.status-pending {
  color: #e6a23c;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  width: 400px;
  max-width: 90%;
}

.modal-content h3 {
  color: #333;
  margin-bottom: 20px;
}

.password-form .form-group {
  margin-bottom: 15px;
}

.password-form label {
  display: block;
  margin-bottom: 5px;
  color: #606266;
}

.password-form input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.modal-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.confirm-btn,
.close-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  flex: 1;
}

.confirm-btn {
  background-color: #409eff;
  color: #fff;
}

.confirm-btn:hover {
  background-color: #66b1ff;
}

.close-btn {
  background-color: #f0f2f5;
  color: #606266;
}

.close-btn:hover {
  background-color: #e6e8eb;
}
</style>